<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/saiki.jpeg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/saiki.jpeg?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java,Effective Java,">










<meta name="description" content="Advantage 1. name　静态工厂方法可以通过方法的名字很直接的传递方法很多信息,而不像传统的构造方法一样名字只能和类名相同,用户只能通过传递的参数和注释文档来判断调用哪个方法.一个很好的例子: 有一个RandomIntGenerator 类，产生随机的int类型的整数。如下所示：123456public class RandomIntGenerator &amp;#123;private fi">
<meta name="keywords" content="Java,Effective Java">
<meta property="og:type" content="article">
<meta property="og:title" content="《Effective Java》Item1. Consider static factory methods instead of constructors">
<meta property="og:url" content="http://yoursite.com/2019/05/28/Item1. Consider static factory methods instead of constructors/index.html">
<meta property="og:site_name" content="Penn">
<meta property="og:description" content="Advantage 1. name　静态工厂方法可以通过方法的名字很直接的传递方法很多信息,而不像传统的构造方法一样名字只能和类名相同,用户只能通过传递的参数和注释文档来判断调用哪个方法.一个很好的例子: 有一个RandomIntGenerator 类，产生随机的int类型的整数。如下所示：123456public class RandomIntGenerator &amp;#123;private fi">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-05-28T03:57:49.250Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《Effective Java》Item1. Consider static factory methods instead of constructors">
<meta name="twitter:description" content="Advantage 1. name　静态工厂方法可以通过方法的名字很直接的传递方法很多信息,而不像传统的构造方法一样名字只能和类名相同,用户只能通过传递的参数和注释文档来判断调用哪个方法.一个很好的例子: 有一个RandomIntGenerator 类，产生随机的int类型的整数。如下所示：123456public class RandomIntGenerator &amp;#123;private fi">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/05/28/Item1. Consider static factory methods instead of constructors/">





  <title>《Effective Java》Item1. Consider static factory methods instead of constructors | Penn</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Penn</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">my blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>
            
            日程表
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>
            
            站点地图
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/05/28/Item1. Consider static factory methods instead of constructors/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Shen">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/saiki.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Penn">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">《Effective Java》Item1. Consider static factory methods instead of constructors</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-28T11:57:49+08:00">
                2019-05-28
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/技术/" itemprop="url" rel="index">
                    <span itemprop="name">技术</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/05/28/Item1. Consider static factory methods instead of constructors/" class="leancloud_visitors" data-flag-title="《Effective Java》Item1. Consider static factory methods instead of constructors">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="Advantage-1-name"><a href="#Advantage-1-name" class="headerlink" title="Advantage 1. name"></a>Advantage 1. name</h3><p>　静态工厂方法可以通过方法的名字很直接的传递方法很多信息,而不像传统的构造方法一样名字只能和类名相同,用户只能通过传递的参数和注释文档来判断调用哪个方法.一个很好的例子:</p>
<p>有一个RandomIntGenerator 类，产生随机的int类型的整数。如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public class RandomIntGenerator &#123;</span><br><span class="line">private final int min;</span><br><span class="line">private final int max;</span><br><span class="line"></span><br><span class="line">public int next() &#123;...&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个生成器接收最大值和最小值两个参数并且生成介于两者之间的随机数。注意到两个属性min和max被final修饰，所以必须初始化它们。可以在定义它们时就初始化或者通过构造器来初始化。通过构造器初始如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public RandomIntGenerator(int min, int max) &#123;</span><br><span class="line">    this.min = min;</span><br><span class="line">    this.max = max;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>现在，我们要提供给这样一个功能，客户端仅设置一个最小值然后产生一个介于此值和Integer.MAX_VALUE之间的整数。所以我们添加了第二个构造器：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public RandomIntGenerator(int min) &#123;</span><br><span class="line">    this.min = min;</span><br><span class="line">    this.max = Integer.MAX_VALUE;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>到目前为止，一切正常。但是，我们同样要提供一个构造器设置一个最大值，然后产生一个介于Integer.MIN_VALUE和最大值的整数。我们添加第三个构造器如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public RandomIntGenerator(int max) &#123;</span><br><span class="line">    this.min = Integer.MIN_VALUE;</span><br><span class="line">    this.max = max;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>如果你这样做了，将会出现编译错误：Duplicate method RandomIntGenerator(int) in type RandomIntGenerator。那里出错了？毫无疑问，问题在于构造器没有名字。因此，一个类仅有一个特定方法签名的构造器。同样的，你不能定义方法签名相同的（返回值、名称、参数类型及个数均相同）两个方法。这就是为什么当我们试着添加构造器RandomIntGenerator(int max) 时，会得到上述的编译错误，原因是我们已经有一个构造器 RandomIntGenerator(int min)。</p>
<p>像这样的情况我们该如何处理呢？幸好有其他方式可以使用：静态工厂方法，通过使用简单的公共静态方法返回一个类的实例。你可能在无意识中已经使用过这种技术。你有没有写过Boolean.valueOf?，就像下面这样：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public static Boolean valueOf(boolean b) &#123;</span><br><span class="line">    return (b ? TRUE : FALSE);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>将静态工厂应用到RandomIntGenerator类，得到<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"> public class RandomIntGenerator &#123;</span><br><span class="line"></span><br><span class="line">    private final int min;</span><br><span class="line">    private final int max;</span><br><span class="line"></span><br><span class="line">    private RandomIntGenerator(int min, int max) &#123;</span><br><span class="line">        this.min = min;</span><br><span class="line">        this.max = max;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static RandomIntGenerator between(int max, int min) &#123;</span><br><span class="line">        return new RandomIntGenerator(min, max);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static RandomIntGenerator biggerThan(int min) &#123;</span><br><span class="line">        return new RandomIntGenerator(min, Integer.MAX_VALUE);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static RandomIntGenerator smallerThan(int max) &#123;</span><br><span class="line">        return new RandomIntGenerator(Integer.MIN_VALUE, max);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public int next() &#123;...&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>注意到构造器被private修饰确保类仅能通过静态工厂方法来初始化。并且当你使用RandomIntGenerator.between(10,20)而不是new RandomIntGenerator(10,20)来产生整数时你的意图被清晰的表达了。值得注意的是，这个技术和 Gang of Four的工厂设计模式不同。此外，任何类可以提供静态工厂方法替代构造器。那么此种技术的优点和缺点是什么呢？我们已经提到过静态工厂方法的第一个优点：静态工厂方法拥有名字。这有两个直接的好处:<br>1.我们可以给静态方法提供一个有意义的名字<br>2.我们可以给静态方法提供参数类型、参数个数相同的几个构造器，在传统构造器中是不能这样做的.</p>
<h3 id="Advantage-2-new-object"><a href="#Advantage-2-new-object" class="headerlink" title="Advantage 2.new object"></a>Advantage 2.new object</h3><p>　　静态工厂方法在调用的时候不需要每次都创建一个新的对象.一个很好的例子是 java.lang.Boolean中的valueOf方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public static Boolean valueOf(boolean b) &#123;</span><br><span class="line">    return (b ? TRUE : FALSE);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>多次调用也不会重复创建对象</p>
<h3 id="Advantage-3-return-any-subtype-of-their-return-type-范型"><a href="#Advantage-3-return-any-subtype-of-their-return-type-范型" class="headerlink" title="Advantage 3.return any subtype of their return type(范型)"></a>Advantage 3.return any subtype of their return type(范型)</h3><p>　　当我们不仅需要返回随机的int值时,我们可以在之前提到的RandomGenerators中加上静态工厂方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public final class RandomGenerators &#123;</span><br><span class="line">    // Suppresses default constructor, ensuring non-instantiability.</span><br><span class="line">    private RandomGenerators() &#123;&#125;</span><br><span class="line"></span><br><span class="line">    public static final RandomGenerator&lt;Integer&gt; getIntGenerator() &#123;</span><br><span class="line">        return new RandomIntGenerator(Integer.MIN_VALUE, Integer.MAX_VALUE);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static final RandomGenerator&lt;String&gt; getStringGenerator() &#123;</span><br><span class="line">        return new RandomStringGenerator(&apos;&apos;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这样需要返回随机字符串时,直接调用RandomGenerator.getStringGenerator().get….<br>另一个例子就是现在经常用到的com.google.common.collect中的Maps.newHaskMap()等.(guava)<br>Advantage 4.返回对象的类型可根据传入的参数变化?<br>　　同样收集new一个HashMap.传统方式</p>
<p>Map&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;();<br> 而用了静态工厂方法<br>public static &lt;K, V&gt; HashMap&lt;K, V&gt; newHashMap() {<br>  return new HashMap&lt;K, V&gt;();<br>}<br>则可以直接<br>Map&lt;String, Integer&gt; map =Maps.newHaskMap()<br>Advantage 5.延迟加载?<br>如JDBC中的</p>
<p>DriverManager.getConnection()<br>调用的时候connection不需要已经建立.</p>
<h3 id="Disadvantage"><a href="#Disadvantage" class="headerlink" title="Disadvantage"></a>Disadvantage</h3><p>1.如果我们在类中将构造函数设为private，只提供静态工厂方法来构建对象，那么我们将不能通过继承扩展该类。<br>但是这也会鼓励我们使用复合而不是继承来扩展类。<br>2.构建对象的静态工厂方法并没有像构造器那样明确标识出来，不能和其他静态方法很方便地区分开来。<br>如果类中只提供静态工厂方法而不是构造器，要想查明如何实例化一个类将会变得困难。<br>我们可以通过遵循静态工厂方法的命名规范来弥补这一劣势：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">valueOf - 返回的实例与它的参数具有相同的值，一般作为类型转换使用，例如Boolean.valueOf(boolean)</span><br><span class="line">of - valueOf的更为简洁的替代。</span><br><span class="line">getInstance - 返回的实例通过方法的参数来描述，但不能说与参数具有同样的值。对于Singleton来说，使用无参getInstance，返回唯一的实例。</span><br><span class="line">newInstance - 像getInstance一样，但其能够确保每次都返回新的对象。</span><br><span class="line">getType - 像getInstance一样，但此方法返回的对象是另一个不同的类。</span><br><span class="line">newType - 像getType一样，但每次返回一个新对象。</span><br></pre></td></tr></table></figure></p>
<p>引用链接:<a href="http://honoka.cnblogs.com。https://yq.aliyun.com/articles/17013" target="_blank" rel="noopener">http://honoka.cnblogs.com。https://yq.aliyun.com/articles/17013</a>.</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>这两个图片是什么?可以扫吗?</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatPay.png" alt="Shen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/aliPay.png" alt="Shen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag"># Java</a>
          
            <a href="/tags/Effective-Java/" rel="tag"># Effective Java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/05/28/Item 10.Obey the general contract when overriding equals/" rel="next" title="《Effective Java》 Item 10.Obey the general contract when overriding equals">
                <i class="fa fa-chevron-left"></i> 《Effective Java》 Item 10.Obey the general contract when overriding equals
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/05/28/Item.18 Favor composition voer inheritance/" rel="prev" title="《Effective Java》Item.18 Favor composition voer inheritance">
                《Effective Java》Item.18 Favor composition voer inheritance <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MjA1OS8xODYwNg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/saiki.jpeg" alt="Shen">
            
              <p class="site-author-name" itemprop="name">Shen</p>
              <p class="site-description motion-element" itemprop="description">Penn's blog</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">117</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Advantage-1-name"><span class="nav-number">1.</span> <span class="nav-text">Advantage 1. name</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Advantage-2-new-object"><span class="nav-number">2.</span> <span class="nav-text">Advantage 2.new object</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Advantage-3-return-any-subtype-of-their-return-type-范型"><span class="nav-number">3.</span> <span class="nav-text">Advantage 3.return any subtype of their return type(范型)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Disadvantage"><span class="nav-number">4.</span> <span class="nav-text">Disadvantage</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Shen</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("Gst71Gv0w5HKejm5H7LuG0XI-gzGzoHsz", "aoFAyHFDKihGTWWhHX0p8byC");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
